package com.lanou.bookstore.category.dao;

import com.lanou.bookstore.category.domain.CBook;
import com.lanou.bookstore.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CBookDao {
    public List<CBook> findAll() {
        List<CBook> cBooks = new ArrayList<>();
        String sql = "SELECT * FROM book";
        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement statement = conn.prepareStatement(sql);

            ResultSet rs = statement.executeQuery();
            // TODO 未完成
            while (rs.next()) {
                CBook CBook = new CBook();
                setCategoryParam(CBook,rs);
               cBooks.add(CBook);
            }
            rs.close();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cBooks;
    }

    public List<CBook> findSE(String cid) {
        List<CBook> cBooks = new ArrayList<>();
        String sql = "SELECT * FROM book WHERE cid = ?";
        Connection conn = JDBCUtil.getConn();
        try {
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1,cid);

            ResultSet rs = statement.executeQuery();
            // TODO 未完成
            while (rs.next()) {
                CBook CBook = new CBook();
                setCategoryParam(CBook, rs);
                cBooks.add(CBook);
            }
            rs.close();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cBooks;
    }

    private void setCategoryParam(CBook CBook, ResultSet rs) throws SQLException {
        String bid=rs.getString("bid");
        String cid=rs.getString("cid");
        String bname=rs.getString("bname");
        Float price=rs.getFloat("price");
        String author=rs.getString("author");
        String img=rs.getString("image");
        CBook.setPrice(price).setAuthor(author).setBname(bname).setImage(img).setBid(bid).setCid(cid);



    }










}


